<?php



declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\common\Sms;
use app\model\Goods;
use app\model\GoodsOrders;
use app\model\School;
use app\model\User;
use app\model\UserCollect;
use app\model\UserCoupon;
use app\model\UserFoot;
use app\tool\Date;
use app\tool\Random;
use DateInterval;
use DatePeriod;
use DateTime;
use GuzzleHttp\Client;
use thans\jwt\facade\JWTAuth;
use think\db\Query;
use think\facade\Config;
use think\facade\Validate;
use think\Request;

class UserController extends BaseController
{
	protected $middleware = [
		'Login' => ['except' => ['register','login','resetpwd']],
	];
	
	
	/**
	 * 注册
	 * @param Request $request
	 * @return void
	 */
	function register(Request $request)
	{
		$mobile = $request->post('mobile');
		$captcha = $request->post('captcha');
		$password = $request->post('password');
		$confirm_password = $request->post('confirm_password');
		$invite_code = $request->post('invite_code');
		$wechatcode = $this->request->post('wechatcode');
		
		if (empty($wechatcode)) {
			$this->writeJson(0, '参数错误');
		}
		
		if (!Validate::is($mobile, 'mobile')) {
			$this->writeJson(0, '手机号格式错误');
		}
		if ($password !== $confirm_password) {
			$this->writeJson(0, '确认密码不一致');
		}
		if (!Validate::is($password, '\S{8,30}')) {
			$this->writeJson(0, '密码必须8-30个字符');
		}
		$user = User::getByMobile($mobile);
		if ($user) {
			$this->writeJson(0, '手机号已被注册');
		}
		$ret = Sms::check($mobile, $captcha, 'register');
		if (!$ret) {
			$this->writeJson(0, '验证码错误');
		}
		$school = School::getByInviteCode($invite_code);
		if (!$school) {
			$this->writeJson(0, '邀请码错误');
		}
		
		
		$client = new Client();
		$appid = Config::get('wechat.wechat_mini.appid');
		$secret = Config::get('wechat.wechat_mini.secret');
		
		//获取接口调用凭据
		$wechattoken = $client->post("https://api.weixin.qq.com/cgi-bin/token", [
			'query' => [
				'appid' => $appid,
				'secret' => $secret,
				'grant_type' => 'client_credential',
			]
		]);
		
		$wechattoken = json_decode($wechattoken->getBody()->getContents());
		if (!isset($wechattoken->access_token)) {
			$this->writeJson(0, '凭据接口调用失败');
		}
		
		$login = $client->get("https://api.weixin.qq.com/sns/jscode2session", [
			'query' => [
				'appid' => $appid,
				'secret' => $secret,
				'js_code' => $wechatcode,
				'grant_type' => 'authorization_code'
			]
		]);
		$wechat = json_decode($login->getBody()->getContents());
		
		if (!isset($wechat->openid)) {
			$this->writeJson(0, $wechat->errmsg);
		}
		
		
		$ip = $request->ip();
		$data['salt'] = Random::alnum();
		$data['password'] = $this->getEncryptPassword($password, $data['salt']);
		$data['avatar'] = '/assets/img/avatar.png'; //设置默认头像。
		$data['mobile'] = $mobile; //设置默认头像。
		$data['logintime'] = time();
		$data['jointime'] = time();
		$data['loginip'] = $ip;
		$data['joinip'] = $ip;
		$data['school_id'] = $school->id;
		$data['openid'] = $wechat->openid;
		$user = User::create($data);
		$token = JWTAuth::builder(['user_id' => $user->id]);
		$this->writeJson(['user' => $user, 'token' => 'Bearer ' . $token]);
	}
	
	/**
	 * 登录
	 * @param Request $request
	 * @return void
	 */
	function login(Request $request)
	{
		$mobile = $request->post('mobile');
		$captcha = $request->post('captcha');
		$password = $request->post('password');
		$login_type = $request->post('login_type'); //1验证码登录  2密码登陆
		if (!Validate::is($mobile, 'mobile')) {
			$this->writeJson(0, '手机号格式错误');
		}
		if (!$user = User::getByMobile($mobile)) {
			$this->writeJson(0, '手机号未注册');
		}
		if ($login_type == 1) {
			$ret = Sms::check($mobile, $captcha, 'login');
			if (!$ret) {
				$this->writeJson(0, '验证码错误');
			}
		} else {
			if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
				$this->writeJson(0, '密码错误');
			}
		}
		$user->logintime = time();
		$user->loginip = $request->ip();
		$user->save();
		$token = JWTAuth::builder(['user_id' => $user->id]);
		$this->writeJson(['user' => $user, 'token' => 'Bearer ' . $token]);
	}
	
	/**
	 * 重置密码
	 * @return void
	 */
	function resetpwd()
	{
		$mobile = $this->request->post("mobile");
		$newpassword = $this->request->post("newpassword");
		$confirm_password = $this->request->post("confirm_password");
		$captcha = $this->request->post("captcha");
		if (!Validate::is($mobile, 'mobile')) {
			$this->writeJson(0, '手机号格式错误');
		}
		if (!Validate::is($newpassword, '\S{8,30}')) {
			$this->writeJson(0, '密码必须8-30个字符');
		}
		if ($newpassword !== $confirm_password) {
			$this->writeJson(0, '确认密码不一致');
		}
		$user = User::getByMobile($mobile);
		if (!$user) {
			$this->writeJson(0, '手机号未注册');
		}
		$ret = Sms::check($mobile, $captcha, 'resetpwd');
		if (!$ret) {
			$this->writeJson(0, '验证码错误');
		}
		Sms::flush($mobile, 'resetpwd');//清空验证码
		$salt = Random::alnum();
		$newpassword = $this->getEncryptPassword($newpassword, $salt);
		$user->password = $newpassword;
		$user->salt = $salt;
		$user->loginfailure = 0;
		$user->save();
		$this->writeJson();
	}
	
	/**
	 * 获取|编辑  用户信息
	 * @return void
	 */
	function userInfo(Request $request)
	{
		$row = User::findOrFail($this->user_id);
		if (!$request->isPost()){
			$this->writeJson($row);
		}
		$params = $request->param();
		$row->data(array_filter($params));
		$row->save();
		$this->writeJson();
	}

	
	/**
	 * 获取用户订单角标
	 * @return void
	 * @throws \think\db\exception\DbException
	 */
	function getOrderTips()
	{
		$data = [
			'status_1'=> GoodsOrders::where(['user_id' => $this->user_id,'status' => 0])->count(),
			'status_2'=> GoodsOrders::where(['user_id' => $this->user_id,'status' => 1])->count(),
			'status_3'=> GoodsOrders::where(['user_id' => $this->user_id,'status' => 2])->count(),
			'status_4'=> GoodsOrders::where(['user_id' => $this->user_id,'status' => 3])->count(),
		];
		$this->writeJson($data);
	}
	
	/**
	 * 获取优惠券数量
	 * @return void
	 * @throws \think\db\exception\DbException
	 */
	function getCouponCount()
	{
		$status_1 = UserCoupon::where(['user_id' => $this->user_id,'status' => 0])->where('expiretime', '>=', time())->count();
		$status_2 = UserCoupon::where(['user_id' => $this->user_id,'status' => 1])->count();
		$status_3 = UserCoupon::where(['user_id' => $this->user_id,'status' => 0])->where('expiretime', '<', time())->count();
		$this->writeJson(['status_1' => $status_1,'status_2' => $status_2,'status_3' => $status_3]);
	}
	
	/**
	 * 获取优惠券列表
	 * @param Request $request
	 * @return void
	 */
	function getCouponList(Request $request)
	{
		$status = $request->get('status/d');
		$rows = UserCoupon::where(['user_id' => $this->user_id])
			->when(!empty($status), function (Query $query) use ($status) {
				if ($status==1){
					$query->where('status', 0)->where('expiretime', '>=', time());
				}
				if ($status==2){
					$query->where('status', 1);
				}
				if ($status==3){
					$query->where('status', 0)->where('expiretime', '<', time());
				}
			})
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	/**
	 * 查看足迹
	 * @param Request $request
	 * @return void
	 * @throws \Exception
	 */
	function getFoot(Request $request)
	{
		$type = $request->get('type/d');
		$startdate = $request->get('startdate','');
		$enddate = $request->get('enddate','');
		$data = [];
		$days=[];
		switch ($type){
			case 1:
				//今天
				$days = [date("Y-m-d",strtotime("today"))];
				break;
			case 2:
				//昨天
				$days = [date("Y-m-d",strtotime('yesterday'))];
				break;
			case 3:
				//近7天
				$days = Date::getEveryDayByRecentDate(7);
				break;
			case 4:
				//近30天
				$days = Date::getEveryDayByRecentDate(30);
				break;
			case 5:
				//自定义时间
				$start = new DateTime($startdate); // 开始日期
				$end = new DateTime($enddate);   // 结束日期
				// 创建一个 DatePeriod 对象，表示从 $start 到 $end 这段时间内的所有日期
				$period = new DatePeriod($start, new DateInterval('P1D'), $end);
				foreach ($period as $day) {
					$days[] = $day->format("Y-m-d");
				}
				break;
			default:
				$this->writeJson(0, '参数错误');
		}
		foreach ($days as $day){
			$goods_ids = UserFoot::where(['user_id' => $this->user_id])->whereDay('createtime',$day)->column('goods_id');
			$list = Goods::withMin(['spec' => 'price'], 'price')->whereIn('id',$goods_ids)->select();
			$data[] = ['day'=>$day,'list'=>$list];
		}
		
		$this->writeJson($data);
		
	}
	
	/**
	 * 清空足迹
	 * @return void
	 */
	function clearFoot()
	{
		UserFoot::where(['user_id'=>$this->user_id])->delete();
		$this->writeJson();
	}
	
	function collect()
	{
		
		$rows = UserCollect::with(['goods'=>function (Query $query) {
			$query->withMin(['spec'=>'price'],'price')->filter(function ($data){
				$data->images = explode(',', $data->images);
				$data->videos = explode(',', $data->videos);
			});
		}])
			->where(['user_id'=>$this->user_id])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	
	
}
